package com.wframe.project.jnd.services.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.wframe.project.jnd.dao.*;
import com.wframe.project.jnd.entity.Picture;
import com.wframe.project.jnd.vo.Product;
import com.wframe.project.jnd.services.OrderService;
import com.wframe.project.jnd.services.PromotionService;
import com.wframe.project.jnd.util.TransformUtils;
import com.wframe.project.jnd.vo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.wframe.project.former.entity.ProductsAttrvalBean;
import com.wframe.project.jnd.services.ProductService;

@Service
public class ProductServiceImpl implements ProductService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ProductDao productDao;
    @Autowired
    InformationDao infoDao;
    @Autowired
    CommonDao commonDao;
    @Autowired
    UserDao userDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderService orderService;
    @Autowired
    private PromotionService promotionService;
    @Autowired
    private PromotionDao promotionDao;
    @Autowired
    private CouponDao couponDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageResult queryWebProduct(JdataBean parms, int size, int pageno) throws Exception {
        PageResult pr = productDao.queryWebProduct(parms, size, pageno);
        List<JdataBean> list = pr.getList();
        for (JdataBean product : list) {
            String photo = product.getString("photoview");
            product.put("amount", product.getInt("amount"));
            if (StringUtils.isBlank(photo)) photo = product.getString("product_photoview");
            product.put("photo", photo);
            String attrjson = product.getString("attrvals");
            if (StringUtils.isNotBlank(attrjson)) {
                //将商品属性取出
                try {
                    List<ProductsAttrvalBean> jsonarr = JSON.parseArray(attrjson, ProductsAttrvalBean.class);
                    for (ProductsAttrvalBean attrbean : jsonarr) {
                        product.put(attrbean.getAttrcode(), attrbean.getValtxt());
                    }
                } catch (Exception ew) {
                    log.error("JSONERROR-商品id:" + product.getString("productid") + "=" + attrjson, ew);
                }
            }
        }
        return pr;
    }

    public PageResult queryChannelProduct(String code, int size, int pageno) {
        return productDao.queryChannelProduct(code, size, pageno);
    }

    /**
     * 加载专题栏目商品
     */
    public JdataBean querySubjectProduct(String userid, String channelcode) {
        JdataBean channel = infoDao.getChannel(channelcode);
        List<Map> subchannels = infoDao.querySubChannel(channelcode);
        for (Map sub : subchannels) {
            PageResult pr = productDao.ChannelProductSort(sub.get("code").toString(), 100, 1);
            //queryControlsales(userid, pr.getList());//控销
            //queryPricegrade(userid, pr.getList());//价格等级
            List<Map> productlist = pr.getList();
            if (StringUtils.isNotBlank(userid)) {
                queryPricegradeAndControlsales(userid, pr.getList()); //价格等级和控销

                Map<String, Integer> dataIndex = new HashMap<>();
                String[] productIds = new String[productlist.size()];
                for (int i = 0, l = productlist.size(); i < l; i++) {
                    Map product = productlist.get(i);
                    productIds[i] = String.valueOf(product.get("productid"));
                    dataIndex.put(productIds[i], i);
                }
                List<JdataBean> promotionsByProducts = this.promotionDao.findPromotionsByProducts(productIds, userid, 1);
                Iterator<JdataBean> promotionsIterator = promotionsByProducts.iterator();
                while (promotionsIterator.hasNext()) {
                    JdataBean productPromotions = promotionsIterator.next();
                    String proId = productPromotions.getString("id");
                    String pms = productPromotions.getString("pms");
                    Map srcProduct = productlist.get(dataIndex.get(proId));
                    if (srcProduct != null && StringUtils.isNotEmpty(pms)) {
                        List<String> pmList = Arrays.asList(pms.split(","));

                        srcProduct.put("promotion_flash_sale", pmList.contains("0"));
                        srcProduct.put("promotion_buy_send", pmList.contains("1"));
                        srcProduct.put("promotion_money_off", pmList.contains("2"));
                        srcProduct.put("promotion_purchase_gift", pmList.contains("3"));
                        srcProduct.put("promotion_coupon", pmList.contains("4"));

                        if (pmList.contains("0")) {
                            BigDecimal fs_price = productPromotions.getBigDecimal("fs_price");
                            BigDecimal fs_amount = productPromotions.getBigDecimal("fs_amount");
                            if (fs_price != null && fs_amount != null && fs_price.compareTo(BigDecimal.ZERO) > 0 && fs_amount.compareTo(BigDecimal.ZERO) > 0) {
                                srcProduct.put("price_s", srcProduct.get("price"));
                                srcProduct.put("price", fs_price);
                                if (srcProduct.get("amount") == null || new BigDecimal((BigInteger) srcProduct.get("amount")).compareTo(fs_amount) > 0) {
                                    srcProduct.put("amount", fs_amount);
                                }
                            }
                        }
                    }
                }
            }

            sub.put("products", productlist);
        }
        channel.put("sublist", subchannels);
        return channel;
    }

    /**
     * 微信端加载栏目商品
     *
     * @return
     */
    public JdataBean querySubjectProduct1(String userid, String channelcode) {
        JdataBean channel = infoDao.getChannel(channelcode);
        List<Map> subchannels = infoDao.querySubChannel(channelcode);
        for (Map sub : subchannels) {
            PageResult pr = productDao.queryChannelProduct1(sub.get("code").toString(), 100, 1);
            //queryControlsales(userid, pr.getList());//控销
            //queryPricegrade(userid, pr.getList());//价格等级
            List<Map> productlist = pr.getList();
            if (StringUtils.isNotBlank(userid)) {
                queryPricegradeAndControlsales(userid, pr.getList()); //价格等级和控销

                Map<String, Integer> dataIndex = new HashMap<>();
                String[] productIds = new String[productlist.size()];
                for (int i = 0, l = productlist.size(); i < l; i++) {
                    Map product = productlist.get(i);
                    productIds[i] = String.valueOf(product.get("productid"));
                    dataIndex.put(productIds[i], i);
                }
                List<JdataBean> promotionsByProducts = this.promotionDao.findPromotionsByProducts(productIds, userid, 2);
                Iterator<JdataBean> promotionsIterator = promotionsByProducts.iterator();
                while (promotionsIterator.hasNext()) {
                    JdataBean productPromotions = promotionsIterator.next();
                    String proId = productPromotions.getString("id");
                    String pms = productPromotions.getString("pms");
                    Map srcProduct = productlist.get(dataIndex.get(proId));
                    if (srcProduct != null && StringUtils.isNotEmpty(pms)) {
                        List<String> pmList = Arrays.asList(pms.split(","));

                        srcProduct.put("promotion_flash_sale", pmList.contains("0"));
                        srcProduct.put("promotion_buy_send", pmList.contains("1"));
                        srcProduct.put("promotion_money_off", pmList.contains("2"));
                        srcProduct.put("promotion_purchase_gift", pmList.contains("3"));
                        srcProduct.put("promotion_coupon", pmList.contains("4"));

                        if (pmList.contains("0")) {
                            BigDecimal fs_price = productPromotions.getBigDecimal("fs_price");
                            BigDecimal fs_amount = productPromotions.getBigDecimal("fs_amount");
                            if (fs_price != null && fs_amount != null && fs_price.compareTo(BigDecimal.ZERO) > 0 && fs_amount.compareTo(BigDecimal.ZERO) > 0) {
                                srcProduct.put("price_s", srcProduct.get("price"));
                                srcProduct.put("price", fs_price);
                                if (srcProduct.get("amount") == null || new BigDecimal((BigInteger) srcProduct.get("amount")).compareTo(fs_amount) > 0) {
                                    srcProduct.put("amount", fs_amount);
                                }
                            }
                        }
                    }
                }
            }

            sub.put("products", productlist);
        }
        channel.put("sublist", subchannels);
        return channel;
    }

    public JdataBean getProductPrice(String priceid) {
        return productDao.getProductPrice(priceid);
    }

    public JdataBean getProductid(String productid) throws Exception {

        JdataBean productPrice = productDao.getProductid(productid);
        JdataBean pricebean = productDao.getProductPrice(productid);
        List<JdataBean> photos = commonDao.queryPhotos(pricebean.getString("photodataid"));
        productPrice.put("photos", photos);
        if (photos.size() > 0) productPrice.put("photo", photos.get(0).getString("filepath"));
        else productPrice.put("photo", "");
        return productPrice;
    }

    /**
     * 商品详情
     */
    public JdataBean getProductInfo(String priceid) throws Exception {
        JdataBean pricebean = productDao.getProductPrice(priceid);
        JdataBean product = productDao.getProduct(pricebean.getString("productid"));
        product.put("priceid", priceid);
        product.put("price", pricebean.get("price"));
        product.put("price_s", pricebean.get("price_s"));
        product.put("amount", pricebean.getInt("amount"));
        product.put("salesnum", pricebean.get("salesnum"));
        product.put("attrname", pricebean.get("name"));
        product.put("salesnum", pricebean.get("salesnum"));
//        product.put("name",pricebean.get("name"));
        List<JdataBean> productattrs = productDao.getProductAttrs(pricebean.getString("productid"));//获取商品属性和属性值
        for (JdataBean attr : productattrs) {
            if (StringUtils.isNotBlank(attr.getString("code")))
                product.put(attr.getString("code"), attr.getString("valtxt"));
        }
        String photodataid = pricebean.getString("photodataid");//销售图片
        if (StringUtils.isBlank(photodataid)) photodataid = product.getString("photodataid");//商品图片
        List<JdataBean> photos = commonDao.queryPhotos(photodataid);
        product.put("photos", photos);
        if (photos.size() > 0) product.put("photo", photos.get(0).getString("filepath"));
        else product.put("photo", "");

        String clscode = productDao.getProductClsCode(pricebean.getString("productid"));
        String[] codes = clscode.split("\\.");
        String codestr = "";
        for (int i = 1; i < codes.length; i++) {
            if (!codestr.equals("")) codestr += ",";
            String code = "";
            for (int j = 0; j <= i; j++) {
                code += "." + codes[j];
            }
            codestr += "'" + code.substring(1, code.length()) + "'";
        }
        product.put("clscode", clscode);
        product.put("clsnavs", productDao.queryProductClsByCode(codestr));

        return product;
    }

    public List<Map> getProductPrices(String productid) throws Exception {
        return productDao.getProductPrices(productid);
    }

    /**
     * 查询商品属性
     */
    @Override
    public List<Map> getAttrs(String clscode, String[] seleditems) {
        List<Map> attrs = productDao.queryProductAttr(clscode);
        List<Map> itemalls = productDao.queryProductAttrItemAll(clscode);
        for (Map item : itemalls) {
            //属性值归类
            for (Map attr : attrs) {
                if (item.get("attrid").toString().equals(attr.get("id").toString())) {
                    List<Map> items = null;
                    if (attr.get("items") != null) items = (List<Map>) attr.get("items");
                    else items = new ArrayList<Map>();
                    items.add(item);
                    attr.put("items", items);
                }
            }
            if (seleditems != null) {
                for (String selid : seleditems) {
                    if (item.get("code").toString().equals(selid)) {
                        item.put("selected", 1);
                        break;
                    }
                }
            }
        }
        return attrs;
    }

    /**
     * 商品分类下属分类列表
     */
    public List<Map> getProductSubCls(String clscode) throws Exception {
        return productDao.querySubProductClsByCode(clscode);
    }

    /**
     * 根据分类获取分类导航
     */
    public List<Map> queryClsNav(String clscode) {
        String[] clscodes = clscode.split("\\.");
        List<String> clscodearr = new ArrayList<String>();
        if (clscodes.length > 1) clscodearr.add(clscode);
        int n = clscode.lastIndexOf(".");
        while (n != -1) {
            String code = clscode.substring(0, n);
            if (code.split("\\.").length > 1)
                clscodearr.add(code);
            n = code.lastIndexOf(".");
        }
        if (clscodearr.size() > 0) {
            List<Map> list = productDao.queryClsNav(clscodearr.toArray(new String[]{}));
            for (Map cls : list)
                cls.put("sublist", productDao.querySubProductCls(cls.get("pid").toString()));
            return list;
        } else return new ArrayList<Map>();
    }

    public List<Map> queryAttrNav(String[] itemids) {
        return productDao.queryAttrNav(itemids);
    }

    //控销
    public void queryControlsales(String userid, List products) {
        JdataBean user = userDao.getUser(userid);
        JdataBean com = userDao.getUserCompany(userid);
        productDao.queryControlsales(user, com, products);
    }

    /**
     * 商品控消判断
     */
    public boolean getControlsales(String userid, String productid) {
        JdataBean user = null;
        if (StringUtils.isNotBlank(userid)) {
            user = userDao.getUser(userid);
            JdataBean com = userDao.getUserCompany(userid);
            user.put("province", com.getString("province"));
            user.put("city", com.getString("city"));
            user.put("region", com.getString("region"));
        } else user = new JdataBean();
        List<JdataBean> controls = productDao.queryControlsales(userid, user.getString("UserGroup"), user.getString("pricegrade"), user.getString("province"), user.getString("city"), user.getString("region"), new String[]{productid});
        boolean bl = false;
        for (JdataBean control : controls) {
            if (control.getString("productid").equals(productid)) {
                bl = true;//可购买
                break;
            }
        }
        return bl;
    }

    //带有营销商品的价格等级
    public void queryProMotionPricegrade(String userid, List products) {
        List<String> productids = new ArrayList<String>();
        for (int i = 0; i < products.size(); i++) {
            Object obj = products.get(i);
            String id = "";
            if (obj instanceof JdataBean) id = ((JdataBean) obj).getString("productid");
            else id = ((Map) obj).get("productid").toString();
            productids.add(id);
        }
        if (productids.size() > 0 && StringUtils.isNotBlank(userid)) {
            JdataBean user = userDao.getUser(userid);
            List<JdataBean> productData = products;
            String[] productIds = new String[products.size()];

            Map<String, Integer> dataIndex = new HashMap<>();
            if (StringUtils.isNotBlank(user.getString("pricegrade"))) {
                List<JdataBean> prices = productDao.queryPricegrade(user.getString("pricegrade"), productids.toArray(new String[]{}));
                for (JdataBean price : prices) {

                    for (int i = 0; i < products.size(); i++) {
                        JdataBean productSenhle = productData.get(i);
                        dataIndex.put(productSenhle.getString("productid"), i);
                        productIds[i] = productSenhle.getString("productid");
                        Object obj = products.get(i);
                        String productid = "";
                        if (obj instanceof JdataBean) {
                            productid = ((JdataBean) obj).getString("productid");
                            if (productid.equals(price.getString("productid"))) {
                                ((JdataBean) obj).put("price", price.get("price"));//更新价格
                                break;
                            }
                        } else {
                            productid = ((Map) obj).get("productid").toString();
                            if (productid.equals(price.getString("productid"))) {
                                ((Map) obj).put("price", price.get("price"));//更新价格
                                break;
                            }
                        }
                    }
                }
                List<JdataBean> promotionsByProducts = this.promotionDao.findPromotionsByProducts(productIds, userid, 2);
                Iterator<JdataBean> promotionsIterator = promotionsByProducts.iterator();
                while (promotionsIterator.hasNext()) {
                    JdataBean productPromotions = promotionsIterator.next();
                    String proId = productPromotions.getString("id");
                    String pms = productPromotions.getString("pms");
                    JdataBean srcProduct = productData.get(dataIndex.get(proId));
                    if (srcProduct != null && StringUtils.isNotEmpty(pms)) {
                        List<String> pmList = Arrays.asList(pms.split(","));

                        srcProduct.put("promotion_flash_sale", pmList.contains("0"));
                        srcProduct.put("promotion_buy_send", pmList.contains("1"));
                        srcProduct.put("promotion_money_off", pmList.contains("2"));
                        srcProduct.put("promotion_purchase_gift", pmList.contains("3"));
                        srcProduct.put("promotion_coupon", pmList.contains("4"));

                        if (pmList.contains("0")) {
                            BigDecimal fs_price = productPromotions.getBigDecimal("fs_price");
                            BigDecimal fs_amount = productPromotions.getBigDecimal("fs_amount");
                            if (fs_price != null && fs_amount != null && fs_price.compareTo(BigDecimal.ZERO) > 0 && fs_amount.compareTo(BigDecimal.ZERO) > 0) {
                                srcProduct.put("price_s", srcProduct.getBigDecimal("price"));
                                srcProduct.put("price", fs_price);
                                if (srcProduct.getBigDecimal("amount") == null || srcProduct.getBigDecimal("amount").compareTo(fs_amount) > 0) {
                                    srcProduct.put("amount", fs_amount);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //价格等级
    public void queryPricegrade(String userid, List products) {
        List<String> productids = new ArrayList<String>();
        for (int i = 0; i < products.size(); i++) {
            Object obj = products.get(i);
            String id = "";
            if (obj instanceof JdataBean) id = ((JdataBean) obj).getString("productid");
            else id = ((Map) obj).get("productid").toString();
            productids.add(id);
        }
        if (productids.size() > 0 && StringUtils.isNotBlank(userid)) {
            JdataBean user = userDao.getUser(userid);
            if (StringUtils.isNotBlank(user.getString("pricegrade"))) {
                List<JdataBean> prices = productDao.queryPricegrade(user.getString("pricegrade"), productids.toArray(new String[]{}));
                for (JdataBean price : prices) {
                    for (int i = 0; i < products.size(); i++) {
                        Object obj = products.get(i);
                        String productid = "";
                        if (obj instanceof JdataBean) {
                            productid = ((JdataBean) obj).getString("productid");
                            if (productid.equals(price.getString("productid"))) {
                                ((JdataBean) obj).put("price", price.get("price"));//更新价格
                                break;
                            }
                        } else {
                            productid = ((Map) obj).get("productid").toString();
                            if (productid.equals(price.getString("productid"))) {
                                ((Map) obj).put("price", price.get("price"));//更新价格
                                break;
                            }
                        }
                    }
                }
            }

        }

    }

    //查询用户所对应的商品价格和是否控销
    @Override
    public void queryPricegradeAndControlsales(String userid, List products) {
        List<String> productids = new ArrayList<String>();
        for (int i = 0; i < products.size(); i++) {
            Object obj = products.get(i);
            String id = "";
            if (obj instanceof JdataBean) id = ((JdataBean) obj).getString("productid");
            else id = ((Map) obj).get("productid").toString();
            productids.add(id);
        }
        if (productids.size() > 0 && StringUtils.isNotBlank(userid)) {
            List<JdataBean> productList = productDao.queryPricegradeAndControlsales(userid, productids);
            for (JdataBean product : productList) {
                for (int i = 0; i < products.size(); i++) {
                    Object obj = products.get(i);
                    String productid = "";
                    if (obj instanceof JdataBean) {
                        productid = ((JdataBean) obj).getString("productid");
                        if (productid.equals(product.getString("id"))) {
                            ((JdataBean) obj).put("price", product.get("price"));//更新价格
                            ((JdataBean) obj).put("canbuy", product.getString("canbuy"));
                            break;
                        }
                    } else {
                        productid = ((Map) obj).get("productid").toString();
                        if (productid.equals(product.getString("id"))) {
                            ((Map) obj).put("price", product.get("price"));//更新价格
                            ((Map) obj).put("canbuy", product.getString("canbuy"));
                            break;
                        }
                    }
                }
            }

        }
    }


    public PageResult maylike(String priceid, int pagesize, int pageno) {
        JdataBean parms = new JdataBean();
        if (StringUtils.isNotBlank(priceid)) {
            JdataBean pricebean = productDao.getProductPrice(priceid);
            if (pricebean != null) {
                String clscode = productDao.getProductClsCode(pricebean.getString("productid"));
                parms.put("classcode", clscode);
            }
        } else {
            parms.put("ordertype", 2);
            parms.put("orderby", 1);
        }
        PageResult pr = productDao.queryWebProduct(parms, pagesize, pageno);
        List<JdataBean> list = pr.getList();
        for (JdataBean product : list) {
            String photo = product.getString("photoview");
            if (StringUtils.isBlank(photo)) photo = product.getString("product_photoview");
            product.put("photo", photo);
            String attrjson = product.getString("attrvals");
            if (StringUtils.isNotBlank(attrjson)) {
                //将商品属性取出
                try {
                    List<ProductsAttrvalBean> jsonarr = JSON.parseArray(attrjson, ProductsAttrvalBean.class);
                    for (ProductsAttrvalBean attrbean : jsonarr) {
                        product.put(attrbean.getAttrcode(), attrbean.getValtxt());
                    }
                } catch (Exception ew) {
                    log.error("JSONERROR-商品id:" + product.getString("productid") + "=" + attrjson, ew);
                }
            }
        }
        return pr;
    }

    public void addpopularity(String priceid) {
        productDao.addpopularity(priceid);
    }

    /**
     * 商品收藏
     */
    public void favorite(String userid, String priceid, int action) throws Exception {
        if (action == 0) {
            JdataBean pro = productDao.getProductPrice(priceid);
            productDao.addFavorite(userid, priceid, pro.getString("productid"));//收藏
        } else productDao.delFavorite(userid, priceid);//取消收藏
    }

    /**
     * 商品收藏
     */
    public boolean checkfavorite(String userid, String priceid) {
        JdataBean get = productDao.getFavorite(userid, priceid);
        if (get == null) return false;
        else return true;
    }

    public PageResult queryFavorite(String userid, int size, int pageno) {
        return productDao.queryFavorite(userid, size, pageno);
    }

    public PageResult queryHotProducts(int size, int pageno) throws Exception {


        return productDao.queryHotProducts(size, pageno);
    }

    @Override
    public PageResult findFavorites(String userId, int pageSize, int pageNo, boolean isAuth) {
        PageResult favorites = productDao.findFavorites(userId, pageSize, pageNo);
        List<Map> list = favorites.getList();
        if (isAuth) {
            for (Map map : list) {
                map.put("canbuy", isControlsales(userId, map.get("id")));//控销
            }
        }
        for (Map map : list) {
            map.putAll(findBasicProductAttrValByProductId(map.get("id")));//商品属性

            String photo = map.get("photoview") == null ? "" : map.get("photoview").toString();
            if (StringUtils.isBlank(photo)) {
                photo = map.get("product_photoview") == null ? "" : map.get("product_photoview").toString();
            }
            map.put("photo", photo);

            int amount = Integer.parseInt(String.valueOf(map.get("amount")));
            map.put("amount", amount > 0 ? amount : 0);
        }

        favorites.setList(list);
        return favorites;
    }

    /**
     * 控销判断
     *
     * @param userId
     * @return
     */
    public boolean isControlsales(String userId, Object productId) {
        return productDao.isControlsales(userId, productId);
    }

    @Override
    public List<Map> isControlsales(String userId, List<PriceBeanVo> prices) {
        List<String> ids = new ArrayList<String>();
        List<Map> errs = new ArrayList<>();
        for (PriceBeanVo price : prices) {
            String priceId = price.getPriceId();
            if (isControlsales(userId, priceId)) {
                ids.add(priceId);
            }
        }
        if (ids.size() > 0) {
            List<JdataBean> list = orderDao.queryProductBypriceid(ids.toArray(new String[]{}));
            for (JdataBean bean : list) {
                errs.add(bean.getDataMap());
            }
        }
        return errs;
    }

    public Map findBasicProductAttrValByProductId(Object productId) {
        return productDao.findBasicProductAttrValByProductId(productId);
    }

    @Override
    public void deleteFavorites(String userId, String[] ids) {
        productDao.deleteFavorites(userId, ids);
    }

    @Override
    public CartBean findProducts(String userid, List<CartItem> items) throws Exception {
        CartBean result = new CartBean();
        List<CartProductVO> products = new ArrayList<>();
        BigDecimal totalPrice = BigDecimal.ZERO;

        Map<Integer, Map<Integer, Object>> map = new HashMap<>();
        for (CartItem item : items) {
            Map tmp = new HashMap();
            tmp.put("id", item.getId());
            tmp.put("num", item.getCount());
            tmp.put("check", item.isCheck());
            map.put(item.getProductid(), tmp);
        }

        Map keyMap = new HashMap();
        keyMap.put("userid", userid);
        keyMap.put("ids", map.keySet());
        List<JdataBean> list = productDao.findProducts(keyMap);
        for (JdataBean product : list) {
            CartProductVO productVO = TransformUtils.trans(product, CartProductVO.class);

            int productid = product.getInt("productid");
            Map productAttrVal = findBasicProductAttrValByProductId(productid);
            productVO.setB_chanjia(String.valueOf(productAttrVal.get("b_chanjia")));
            productVO.setB_guige(String.valueOf(productAttrVal.get("b_guige")));
            //活动库存
            productVO.setAmount(product.getInt("inventory"));
            //商品购买数量
            Integer cartId = (Integer) map.get(productid).get("id");
            productVO.setCartId(cartId);
            productVO.setOften(orderService.checkOften(userid, String.valueOf(productid)));
            //商品购买数量
            Integer num = (Integer) map.get(productid).get("num");
            productVO.setBuyNum(num);
            //订单项总价
            BigDecimal price = product.getBigDecimal("price").multiply(BigDecimal.valueOf(num));
            productVO.setTotalPrice(price);
            boolean check = (boolean) map.get(productid).get("check");
            productVO.setCheck(check);

            if (check) {
                totalPrice = totalPrice.add(price);
            }
            products.add(productVO);
        }

        result.setTotalPrice(totalPrice);
        result.setProducts(products);
        return result;
    }

    @Override
    public CartBean findProducts(Map<String, CartItem> items, String userid, int platform) {
        CartBean result = new CartBean();
        BigDecimal totalPrice = BigDecimal.ZERO;
        List<CartProductVO> productVOS = new ArrayList<>();
        List<Product> products = findPowerProducts(userid, items.keySet());
        for (Product cartProduct : products) {
            String productid = String.valueOf(cartProduct.getId());
            CartProductVO productVO = new CartProductVO();

            Product base = findOne(productid);
            productVO.setPhoto(base.getPhoto());
            productVO.setName(base.getName());
            productVO.setB_chanjia(base.getManufacturers());
            productVO.setB_guige(base.getSpecification());
            productVO.setUnit(base.getUnit());

            CartItem item = items.get(productid);
            productVO.setId(item.getProductid());
            productVO.setCartId(item.getId());
            boolean check = item.isCheck();
            productVO.setCheck(check);
            //购买数量
            int count = item.getCount();
            productVO.setBuyNum(count);

            productVO.setOften(cartProduct.isFavorite());
            BigDecimal price = cartProduct.getPrice();
            productVO.setPrice(price);
            int amount = cartProduct.getAmount();
            //商品库存
            productVO.setAmount(amount > 0 ? amount : 0);
            //订单项总价
            BigDecimal unitTotalPrice = BigDecimal.ZERO;
            if (check) {
                unitTotalPrice = price.multiply(BigDecimal.valueOf(count));
            }
            productVO.setTotalPrice(unitTotalPrice);

            totalPrice = totalPrice.add(unitTotalPrice);
            productVOS.add(productVO);
        }

        result.setTotalPrice(totalPrice);
        result.setProducts(productVOS);
        return result;
    }

    @Override
    public List<JdataBean> findProducts(String userid, Map<Integer, CartItem> itemMap, int platform) {
        Map<String, Object> parms = new HashMap<>();
        parms.put("userid", userid);
        parms.put("ids", itemMap.keySet());
        parms.put("platform", platform);
        return productDao.findProductsInfo(parms);
    }

    @Override
    public List<Product> findPowerProducts(String userid, Set<String> ids) {
        return productDao.findPowerProducts(userid, StringUtils.join(ids, ","));
    }

    @Override
    public UrgentProduct findCartProduct(String userid, String pid) {
        return productDao.findCartProduct(userid, pid);
    }

    @Override
    public int getAvailableInventory(String productid) {
        return productDao.getAvailableInventory(productid);
    }

    @Override
    public List<JdataBean> getDataidByUserid(String userid) {
        return productDao.getDataidByUserid(userid);
    }

    @Override
    public Product findOne(String priceid) {
        String key = "REDIS_PRODUCT_" + priceid + ":BASE";
        ValueOperations<String, String> operations = redisTemplate.opsForValue();

        try {
            String value = operations.get(key);
            if (StringUtils.isNotBlank(value)) {
                return JSON.parseObject(value, Product.class);
            }
        } catch (Exception e) {
            log.debug("redis服务未启动");
        }

        Product product = productDao.findOne(priceid);
        List<Picture> photos = productDao.findPhotos(priceid);
        String photo = "";
        if (!photos.isEmpty()) {
            photo = photos.get(0).getFilepath();
        }
        product.setPhotos(photos);
        product.setPhoto(photo);

        try {
            operations.set(key, JSON.toJSONString(product), 1, TimeUnit.DAYS);
        } catch (Exception e) {
            log.debug("redis服务未启动");
        }
        return product;
    }

    @Override
    public Product findPowerProduct(String priceid) {
        return productDao.findPowerProduct(priceid);
    }

    @Override
    public Product findPowerProduct(String userid, String priceid) {
        return productDao.findPowerProduct(userid, priceid);
    }

    @Override
    public PageResult findWebProducts(JdataBean parms, int size, int pageno, int platform) {

        PageResult pr = productDao.findWebProducts(parms, size, pageno);
        List<JdataBean> list = pr.getList();
        Map<String, Integer> dataIndex = new HashMap<>();

        String[] productIds = new String[list.size()];
        String userid = parms.getString("userid");

        for (int i = 0, l = list.size(); i < l; i++) {
            JdataBean product = list.get(i);
            productIds[i] = product.getString("id");
            dataIndex.put(product.getString("id"), i);
//            product.put("canbuy", isControlsales(parms.getString("userid"), product.get("productid")));
            String photo = product.getString("photoview");
            product.put("amount", product.getInt("amount"));
            if (StringUtils.isBlank(photo)) photo = product.getString("product_photoview");
            product.put("photo", photo);
            String attrjson = product.getString("attrvals");
            if (StringUtils.isNotBlank(attrjson)) {
                //将商品属性取出
                try {
                    List<ProductsAttrvalBean> jsonarr = JSON.parseArray(attrjson, ProductsAttrvalBean.class);
                    for (ProductsAttrvalBean attrbean : jsonarr) {
                        product.put(attrbean.getAttrcode(), attrbean.getValtxt());
                    }
                } catch (Exception ew) {
                    log.error("JSONERROR-商品id:" + product.getString("productid") + "=" + attrjson, ew);
                }
            }
        }

        List<JdataBean> promotionsByProducts = this.promotionDao.findPromotionsByProducts(productIds, userid, platform);
        Iterator<JdataBean> promotionsIterator = promotionsByProducts.iterator();
        while (promotionsIterator.hasNext()) {
            JdataBean productPromotions = promotionsIterator.next();
            String proId = productPromotions.getString("id");
            String pms = productPromotions.getString("pms");
            JdataBean srcProduct = list.get(dataIndex.get(proId));
            if (srcProduct != null && StringUtils.isNotEmpty(pms)) {
                List<String> pmList = Arrays.asList(pms.split(","));

                srcProduct.put("promotion_flash_sale", pmList.contains("0"));
                srcProduct.put("promotion_buy_send", pmList.contains("1"));
                srcProduct.put("promotion_money_off", pmList.contains("2"));
                srcProduct.put("promotion_purchase_gift", pmList.contains("3"));
                srcProduct.put("promotion_coupon", pmList.contains("4"));

                if (pmList.contains("0")) {
                    BigDecimal fs_price = productPromotions.getBigDecimal("fs_price");
                    BigDecimal fs_amount = productPromotions.getBigDecimal("fs_amount");
                    if (fs_price != null && fs_amount != null && fs_price.compareTo(BigDecimal.ZERO) > 0 && fs_amount.compareTo(BigDecimal.ZERO) > 0) {
                        srcProduct.put("price_s", srcProduct.getBigDecimal("price"));
                        srcProduct.put("price", fs_price);
                        if (srcProduct.getBigDecimal("amount") == null || srcProduct.getBigDecimal("amount").compareTo(fs_amount) > 0) {
                            srcProduct.put("fs_amount", fs_amount);
                        } else {
                            srcProduct.put("fs_amount", srcProduct.getBigDecimal("amount"));
                        }

                    }
                }

            }

        }

        return pr;
    }

    @Override
    public List<JdataBean> findWebProductsBarcode(String barcode, String userid) {

        List<JdataBean> list = productDao.findWebProductsBarcodde(barcode, userid);
        Map<String, Integer> dataIndex = new HashMap<>();

        String[] productIds = new String[list.size()];

        for (int i = 0, l = list.size(); i < l; i++) {
            JdataBean product = list.get(i);

            productIds[i] = product.getString("id");

            dataIndex.put(product.getString("id"), i);

            if (StringUtils.isNotEmpty(userid)) {
                product.put("canbuy", isControlsales(userid, product.get("productid")));
            }

            String photo = product.getString("photoview");
            product.put("amount", product.getInt("amount"));
            if (StringUtils.isBlank(photo)) photo = product.getString("product_photoview");
            product.put("photo", photo);
            String attrjson = product.getString("attrvals");
            if (StringUtils.isNotBlank(attrjson)) {
                //将商品属性取出
                try {
                    List<ProductsAttrvalBean> jsonarr = JSON.parseArray(attrjson, ProductsAttrvalBean.class);
                    for (ProductsAttrvalBean attrbean : jsonarr) {
                        product.put(attrbean.getAttrcode(), attrbean.getValtxt());
                    }
                } catch (Exception ew) {
                    log.error("JSONERROR-商品id:" + product.getString("productid") + "=" + attrjson, ew);
                }
            }
        }

        if (StringUtils.isNotEmpty(userid)) {
            List<JdataBean> promotionsByProducts = this.promotionDao.findPromotionsByProducts(productIds, userid, 2);
            Iterator<JdataBean> promotionsIterator = promotionsByProducts.iterator();
            while (promotionsIterator.hasNext()) {
                JdataBean productPromotions = promotionsIterator.next();
                String proId = productPromotions.getString("id");
                String pms = productPromotions.getString("pms");
                JdataBean srcProduct = list.get(dataIndex.get(proId));
                if (srcProduct != null && StringUtils.isNotEmpty(pms)) {
                    List<String> pmList = Arrays.asList(pms.split(","));

                    srcProduct.put("promotion_flash_sale", pmList.contains("0"));
                    srcProduct.put("promotion_buy_send", pmList.contains("1"));
                    srcProduct.put("promotion_money_off", pmList.contains("2"));
                    srcProduct.put("promotion_purchase_gift", pmList.contains("3"));
                    srcProduct.put("promotion_coupon", pmList.contains("4"));

                    if (pmList.contains("0")) {
                        BigDecimal fs_price = productPromotions.getBigDecimal("fs_price");
                        BigDecimal fs_amount = productPromotions.getBigDecimal("fs_amount");
                        if (fs_price != null && fs_amount != null && fs_price.compareTo(BigDecimal.ZERO) > 0 && fs_amount.compareTo(BigDecimal.ZERO) > 0) {
                            srcProduct.put("price_s", srcProduct.getBigDecimal("price"));
                            srcProduct.put("price", fs_price);
                            if (srcProduct.getBigDecimal("amount") == null || srcProduct.getBigDecimal("amount").compareTo(fs_amount) > 0) {
                                srcProduct.put("amount", fs_amount);
                            }
                        }
                    }
                }
            }
        }

        return list;
    }

    @Override
    public BigDecimal findAppositePrice(String userid, String productid) {
        return productDao.findAppositePrice(userid, productid);
    }

    @Override
    public PageResult findHotProducts(String userId, int pageSize, int pageNo) {
        return productDao.findHotProducts(userId, pageSize, pageNo);
    }

}
